package com.kpx.app.fragment;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.kpx.app.R;
import com.kpx.app.activity.ActivityInvaliteFriend;
import com.kpx.app.activity.ActivityMain;
import com.kpx.app.activity.ActivityMessageShow;
import com.kpx.app.activity.ActivityMessgeList;
import com.kpx.app.activity.ActivityMyTGList;
import com.kpx.app.activity.ActivityWebShow;
import com.kpx.app.adapter.TuiGuangAdapter;
import com.kpx.app.base.FragmentBase;
import com.kpx.app.bean.BannerBean;
import com.kpx.app.bean.LoginUser;
import com.kpx.app.bean.MenuBean;
import com.kpx.app.bean.QDinfoBean;
import com.kpx.app.bean.TGMainBean;
import com.kpx.app.bean.TGbean;
import com.kpx.app.bean.Wallet;
import com.kpx.app.cache.FileCache;
import com.kpx.app.configs.Constants;
import com.kpx.app.http.HttpDataApi;
import com.kpx.app.http.HttpDataLoader;
import com.kpx.app.http.HttpDataReqUrl;
import com.kpx.app.http.HttpDataRequest;
import com.kpx.app.http.ResObj;
import com.kpx.app.utils.MyHashMap;
import com.kpx.app.utils.StringUtil;
import com.kpx.app.utils.TimeUtil;
import com.kpx.app.utils.UIUtils;
import com.kpx.app.utils.UserInfoUtils;
import com.kpx.app.utils.uiutils.DisplayUtil;
import com.kpx.app.utils.uiutils.IntentUtil;
import com.kpx.app.utils.uiutils.ToastUtil;
import com.kpx.app.view.ImageCycleView;
import com.kpx.app.view.TitleView;
import com.kpx.app.view.ViewMainTj;
import com.kpx.app.wigdet.AutoSizeListView;
import com.kpx.app.wigdet.QDshowDialog;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoaderInterface;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/12/20.
 * 首页
 */
public class FragmentMain extends FragmentBase {
    @BindView(R.id.viewFlowView)
    ImageCycleView viewFlowView;
    //    @BindView(R.id.my_banner)
//    Banner banner;
    @BindView(R.id.txt_purse_price)
    TextView txtPursePrice;
    @BindView(R.id.txt_price_today)
    TextView txtPriceToday;
    @BindView(R.id.txt_price_month)
    TextView txtPriceMonth;
    @BindView(R.id.txt_price_tuiguang)
    TextView txtPriceTuiguang;
    @BindView(R.id.ll_task_go)
    LinearLayout llTaskGo;
    @BindView(R.id.txt_qiandao)
    TextView txtQiandao;
    @BindView(R.id.txt_tj_more)
    TextView txtTjMore;
    @BindView(R.id.btn_tg_now)
    Button btnTgNow;
    @BindView(R.id.aslv_my_tuiguangs)
    AutoSizeListView aslvMyTuiguangs;
    @BindView(R.id.titleview)
    TitleView titleview;
    DecimalFormat df = new DecimalFormat("###0.00");
    @BindView(R.id.txt_study_new)
    TextView txtStudyNew;
    @BindView(R.id.txt_invalite_friend)
    TextView txtInvaliteFriend;
    @BindView(R.id.type_item_swipfreshlayout)
    SwipeRefreshLayout mSwipeRefreshLayout;
    private List<TGbean> tlist = new ArrayList<>();
    private TuiGuangAdapter adapter;
    private DisplayImageOptions options;

    @Override
    public int setLayout() {
        return R.layout.fragment_main;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        UIUtils.setNormalTitle(titleview, "全民快拍秀");
        titleview.setTitleColor(getResources().getColor(R.color.white));
        titleview.setRight(R.drawable.to_msg_center, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentUtil.gotoActivity(getActivity(), ActivityMessageShow.class);
            }
        });
        titleview.setLeftVisible(false);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary, R.color.colorAccent, R.color.colorPrimaryDark);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                setData();
                getBanner();
            }
        });
        //实现首次自动显示加载提示
        mSwipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                mSwipeRefreshLayout.setRefreshing(true);
            }
        });
        adapter = new TuiGuangAdapter(getActivity(), tlist, R.layout.item_tuiguang_show);
        aslvMyTuiguangs.setAdapter(adapter);
        // 设置下载的图片是否缓存在内存中
        options = new DisplayImageOptions.Builder()
                .cacheInMemory(true) // 设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)
                .build();
        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setData();
        getBanner();
//        UIUtils.iniBanner(getActivity(), banner);
//        //如果你想用自己项目的图片加载,那么----->自定义图片加载框架
//        banner.setOnBannerListener(new OnBannerListener() {
//            @Override
//            public void OnBannerClick(int position) {
//
//            }
//        });
    }

    private void getTjCategerys() {
        UserInfoUtils.getTaskCategerys(getActivity(), 0, new UserInfoUtils.OnGetCategerysBackListener() {
            @Override
            public void back(ArrayList<MenuBean> menus) {
                if (menus != null) {
                    addTj(menus);
                }
            }
        });
    }

    private void addTj(final ArrayList<MenuBean> menus) {
        llTaskGo.removeAllViews();
        for (int i = 0; i < menus.size(); i++) {
            ViewMainTj v = new ViewMainTj(getContext());
            v.setData(menus.get(i), new ViewMainTj.OnclickBackListener() {
                @Override
                public void toback(MenuBean b) {
                    ((ActivityMain) getActivity()).changeTab(b);
                }
            });
            v.setTag(i);
            llTaskGo.addView(v);
            DisplayUtil.setViewWH_L_new(getContext(), v, 1, 4, 26);
        }
        ViewMainTj v = new ViewMainTj(getContext());
        v.setData(new String[]{"", ""}, new ViewMainTj.OnclickBackListener() {
            @Override
            public void toback(MenuBean b) {
                ((ActivityMain) getContext()).changeTab(b);
            }
        });
        v.setTag(-1);
        llTaskGo.addView(v);
        DisplayUtil.setViewWH_L_new(getContext(), v, 1, 4, 26);
    }

    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
//        banner.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
//        banner.stopAutoPlay();
    }

    private void getBanner() {
        ArrayList<BannerBean> cacgebanners = (ArrayList<BannerBean>) FileCache.sharedInstance().get(Constants.KEY_BANNER_LIST);
        if (cacgebanners != null) {
//            banner.setImages(cacgebanners);
//            //banner设置方法全部调用完毕时最后调用
//            banner.start();
            showBanner(cacgebanners);
        }
        MyHashMap map = new MyHashMap();
        map.put("platform", "1");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                mSwipeRefreshLayout.setRefreshing(false);
                if (result.getCode() == 0) {
                    ArrayList<BannerBean> banners = (ArrayList<BannerBean>) result.getData();
                    if (banners != null) {
                        FileCache.sharedInstance().put(Constants.KEY_BANNER_LIST, banners);
                        showBanner(banners);
//                        banner.setImages(banners);
//                        banner.start();
                    }
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                mSwipeRefreshLayout.setRefreshing(false);
                ToastUtil.getInstance().showToast(getActivity(), error);
            }

        }, BannerBean.class, HttpDataRequest.TYPE_LIST).POST(HttpDataReqUrl.URL_POST_GET_BANNER, true, map);
    }

    private void showBanner(ArrayList<BannerBean> cacgebanners) {
        viewFlowView.setImageResources(cacgebanners, new ImageCycleView.ImageCycleViewListener() {
            @Override
            public void displayImage(String imageURL, ImageView imageView) {
                ImageLoader.getInstance().displayImage(imageURL, imageView, options);
//                Glide.with(getActivity())
//                        .load(imageURL)
//                        .fitCenter()
//                        .placeholder(R.drawable.default_head_img)
//                        .crossFade()
//                        .into((ImageView) imageView);
            }

            @Override
            public void onImageClick(BannerBean info, int postion, View imageView) {
                String url = info.getLinkUrl();
                if (!TextUtils.isEmpty(url) && (url.startsWith("http://") || url.startsWith("https://"))) {
                    ActivityWebShow.type = 2;
                    ActivityWebShow.url = url;
                    ActivityWebShow.title = info.getPromptText();
                    IntentUtil.gotoActivity(getActivity(), ActivityWebShow.class);
                }
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        if (UserInfoUtils.isUserLogin()) {
            btnTgNow.setText("立即推广");
        } else {
            btnTgNow.setVisibility(View.VISIBLE);
            tlist.clear();
            adapter.setData(tlist);
            btnTgNow.setText("立即登录");
            txtPursePrice.setText(Html.fromHtml(toHtml(StringUtil.formatAmount(df.format(0), 2))));//账号余额//账号余额
            txtPriceToday.setText("0.0");//账号余额
            txtPriceMonth.setText("0.0");//账号余额
            txtPriceTuiguang.setText("0.0");//账号余额
        }
        setData();
        getBanner();
    }

    private void setData() {
        if (UserInfoUtils.isUserLogin()) {
            LoginUser loginUser = UserInfoUtils.getCachedLoginUser();
            if (loginUser != null) {
                Wallet wallet = loginUser.getWALLET();
                if (wallet != null) {
                    txtPursePrice.setText(Html.fromHtml(toHtml(StringUtil.formatAmount(df.format(wallet.getTotalAmount()), 2))));//账号余额
                    txtPriceToday.setText(df.format(wallet.getTodayIncome()));//今日收入
                    txtPriceMonth.setText(df.format(wallet.getNowMonthIncome()));//本月收入
                    txtPriceTuiguang.setText(df.format(wallet.getNowMonthExtendIncome()));//推广收入
                }
            }
            getTGlist();
        }
        getTjCategerys();
    }

    private String toHtml(String money) {
        String[] arr = money.split("[.]");
        if (arr.length > 1) {
            return "<big>" + arr[0] + "</big>" + "<small>." + arr[1] + "</small>";
        } else {
            return "<big>" + money + "</big>" + "<small>.00</small>";
        }
    }

    /**
     * 获取推广列表
     */
    private void getTGlist() {
        MyHashMap map = new MyHashMap();
        map.put("pageIndex", "1");
        map.put("pageSize", "10");
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                if (result.getCode() == 0) {
                    TGMainBean b = (TGMainBean) result.getData();
                    if (b != null && b.getMainList() != null) {
                        tlist.clear();
                        tlist.addAll(b.getMainList());
                        adapter.setData(tlist);
                        if (tlist.size() > 0) {
                            btnTgNow.setVisibility(View.GONE);
                        } else {
                            btnTgNow.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                ToastUtil.getInstance().showToast(getActivity(), error);
            }
        }, TGMainBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_POST_GET_TG_LIST, true, map);
    }

    @OnClick({R.id.txt_qiandao, R.id.txt_study_new, R.id.txt_invalite_friend, R.id.btn_tg_now, R.id.txt_tj_more})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.txt_qiandao://签到
                toShowQD();
//                UIUtils.goJd(getActivity(),"");
//                UIUtils.gotb(getActivity(),"");
//                UIUtils.gotm(getActivity(),"");

                break;
            case R.id.txt_study_new://新手学习
                ((ActivityMain) getActivity()).changeToHelp();
                break;
            case R.id.txt_tj_more:
                if (!UserInfoUtils.isUserLogin()) {
                    UserInfoUtils.showLoginDialog(getActivity(), "立即登录", 0);
                } else {
                    IntentUtil.gotoActivity(getActivity(), ActivityMyTGList.class);
                }
                break;
            case R.id.btn_tg_now:
                if (!UserInfoUtils.isUserLogin()) {
                    UserInfoUtils.showLoginDialog(getActivity(), "立即登录", 0);
                } else {
                    IntentUtil.gotoActivity(getActivity(), ActivityInvaliteFriend.class);
                }
                break;
            case R.id.txt_invalite_friend://推荐好友
                if (!UserInfoUtils.isUserLogin()) {
                    UserInfoUtils.showLoginDialog(getActivity(), "立即登录", 0);
                } else {
                    IntentUtil.gotoActivity(getActivity(), ActivityInvaliteFriend.class);
                }
                break;
        }
    }

    /**
     * 查询签到信息
     */
    private void toCheckQD() {
        showLoadingDialog(getActivity());
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog(getActivity());
                if (result.getCode() == 0) {
                    QDinfoBean b = (QDinfoBean) result.getData();
                    if (b != null) {
                        QDshowDialog dshowDialog = new QDshowDialog(getActivity());
                        dshowDialog.setData(b);
                        dshowDialog.show();
                    }
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog(getActivity());
                ToastUtil.getInstance().showToast(getActivity(), error);
            }

        }, QDinfoBean.class, HttpDataRequest.TYPE_OBJECT).POST(HttpDataReqUrl.URL_GET_CHECK_QIANDAO, true, map);
    }

    /**
     * 进行签到功能
     */
    private void toShowQD() {
        showLoadingDialog(getActivity());
        MyHashMap map = new MyHashMap();
        new HttpDataLoader(new HttpDataApi.OnRequestCallback() {
            @Override
            public void onRequestSuccess(String url, ResObj result, boolean isFrmCache) {
                dissmissLoadingDialog(getActivity());
                if (result.getCode() == 0) {
                    toCheckQD();
                    ToastUtil.getInstance().showToast(getActivity(), "签到成功");
                } else {
                    ToastUtil.getInstance().showToast(getActivity(), result.getMsg());
                }
            }

            @Override
            public void onRequestError(String url, int statusCode, String error) {
                dissmissLoadingDialog(getActivity());
                ToastUtil.getInstance().showToast(getActivity(), error);
            }

        }, null, null).POST(HttpDataReqUrl.URL_GET_TO_QIANDAO, true, map);
    }
}
